package com.rocksea.app.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;

import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.DataBaseConfig;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.SQLiteHelper;

import java.util.ArrayList;

/**
 * @author by Mrw_v @date on 2018/10/22
 */

public class PileIdDbHelper implements SQLiteHelper.OnUpdateListener
{
    private static LiteOrm mLiteOrm;

    public static void init(Context context)
    {
        DataBaseConfig config = new DataBaseConfig(context);
        config.dbName = Environment.getExternalStorageDirectory().getPath()+"/RailDatabase/db/PileId.db";
        config.dbVersion = 1;
        mLiteOrm = LiteOrm.newSingleInstance(config);
        PileId demo = new PileId();
        mLiteOrm.save(demo);
        mLiteOrm.delete(demo);
    }

    @Override
    public void onUpdate(SQLiteDatabase sqLiteDatabase, int i, int i1)
    {

    }

    public static void insert(ArrayList<PileId> pileIds)
    {
        mLiteOrm.insert(pileIds);
    }

    public static void insert(PileId pileId)
    {

        if (mLiteOrm != null)
        {
            if (queryCount(pileId.planNum,pileId.pileNo) == 0)
                mLiteOrm.save(pileId);
        }
    }

    public static long queryCount(String planNum,String pileNo)
    {
        QueryBuilder<PileId> queryBuilder = new QueryBuilder<>(PileId.class);
        queryBuilder.where("planNum = ? AND pileNo = ?",new Object[]{planNum,pileNo});
        if (mLiteOrm == null)
            return 0;
        return mLiteOrm.queryCount(queryBuilder);
    }


    public static PileId queryPlanIdAndPileId(String planNum,String pileNo)
    {
        String sql = "SELECT *FROM PileId WHERE planNum = ? AND pileNo = ?";
        Cursor cursor = mLiteOrm.getWritableDatabase().rawQuery(sql,new String[]{planNum,pileNo});
        if (cursor.moveToFirst())
        {
            do {
                long planId = cursor.getLong(cursor.getColumnIndex("planId"));
                long pileId = cursor.getLong(cursor.getColumnIndex("pileId"));
                cursor.close();
                return new PileId(planNum,pileNo,planId,pileId);
            }while (cursor.moveToNext());
        }
        cursor.close();
        return new PileId();
    }
}
